package com.sgb.member.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberTypeBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberPersonBean;
import com.sgb.member.ui.activity.ChooseMemberTypeActivity;
import com.sgb.member.ui.activity.MemberManageActivity;
import com.sgb.member.ui.activity.MemberModifyActivity;
import com.sgb.member.ui.adapter.MemberCommonAdapter;
import com.sgb.member.ui.adapter.MemberCommonPersonAdapter;
import com.sgb.member.view_model.MemberTypeDemandModel;
import com.sgb.member.weight.MemberCallback;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

/**
 * 会员管理 - 需方会员
 */
public class MemberTypeDemandFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener
        , XChooseDialog.DialogCallBackImpl, MemberCallback {
    @Inject
    MemberTypeDemandModel mModel;
    private FragmentMemberTypeBinding mBind;
    /**
     * 会员主体
     */
    private String mNo01 = "1"; // 会员主体
    /**
     * 会员类型
     */
    private String mNo0; // 会员类型
    /**
     * 会员类型
     */
    private String mNo1; // 会员类型二级
    /**
     * 企业类型
     */
    private String mNo2; // 企业类型
    /**
     * 会员等级
     */
    private String mNo3; // 会员等级
    /**
     * 经营地址 省
     */
    private String mNo4; // 经营地址
    /**
     * 经营地址 市
     */
    private String mNo41; // 经营地址
    /**
     * 资质类型
     */
    private String mNo5; // 资质类型
    /**
     * 资质等级
     */
    private String mNo51;// 资质等级
    /**
     * 荣誉分类
     */
    private String mNo6; // 荣誉分类
    /**
     * 固定资产
     */
    private String mNo7; // 固定资产
    /**
     * 知识产权
     */
    private String mNo8; // 知识产权
    /**
     * 单次业绩最大金额
     */
    private String mNo9; // 单次业绩最大金额
    /**
     * 是否有招采信息
     */
    private String mNo10;// 是否有招采信息
    /**
     * 企业关注的会员 type : 1需方会员 2供方会员
     */
    private String mNo11 = "1";
    private CommonPopEntity mAll;
    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private String mAddressCurName; // 初始化设置经营地址

    /**
     * 修改会员类型弹框
     */
    private OptionsPickerView<CommonPopEntity> mOption;
    private List<CommonPopEntity> mPotionData;

    private MemberCommonAdapter myMemberAdapter;
    private MemberCommonPersonAdapter mPersonAdapter;
    private int mPosition;

    public MemberTypeDemandFragment() {
    }

    public static MemberTypeDemandFragment newInstance(int position, int cateType, CommonPopEntity entity) {
        MemberTypeDemandFragment fragment = new MemberTypeDemandFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putInt("CATE_TYPE", cateType);
        bundle.putSerializable("CATE_OBJECT", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBind = DataBindingUtil.inflate(inflater, R.layout.fragment_member_type, container, false);
        return mBind.getRoot();
    }

    @Override
    protected void initView() {
        if (getArguments() == null) return;
        mPosition = getArguments().getInt("INDEX", 0); // 界面下标
        initChooseDialog();
        initPopup();
        initRecycler();
        // 初始化筛选值
        int cateType = getArguments().getInt("CATE_TYPE", -1); // 会员分类跳转传输下标
        CommonPopEntity cateEntity = (CommonPopEntity) getArguments().getSerializable("CATE_OBJECT"); // 会员分类跳转传输筛选项
        if (cateEntity != null) {
            switch (cateType) {
                case 0: // 会员类型
                    mNo0 = cateEntity.getNo();
                    mBind.popup1.refreshChoose(mNo0, cateEntity.getTypeName(), cateEntity.getCurPos() + 1);
                    break;
                case 1: // 会员等级
                    mNo3 = cateEntity.getNo();
                    mBind.popupMemberLever.refreshChoose(mNo3, cateEntity.getTypeName(), cateEntity.getCurPos() + 1);
                    break;
                case 2: // 经营地址
                    mNo4 = cateEntity.getNo();
                    mAddressCurName = cateEntity.getTypeName();
                    mBind.popup4.updateChooseTextStatus(1, cateEntity.getTypeName());
                    break;
            }
        }

    }

    @Override
    protected void onLazyLoad() {
       // loadData(false);
        loadOtherData();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData(false);
    }

    public void loadData(boolean isLoadMore) {
        String searchText = getActivity() == null ? "" : ((MemberManageActivity) getActivity()).getSearchText();
        switch (mPosition) {
            case 0:
                // 需方会员
                mModel.getJoinMembers(isLoadMore, searchText, mNo01, mNo0, mNo1, mNo2, mNo3, mNo4, mNo41, mNo5, mNo6, mNo7, mNo8, mNo9, mNo10);
                break;
            case 1:
                // 供方会员
                mModel.getMyMembers(isLoadMore, searchText, mNo01, mNo0, mNo1, mNo2, mNo3, mNo4, mNo41, mNo5, mNo6, mNo7, mNo8, mNo9, mNo10);
                break;
        }
    }

    private boolean loadOtherData() {
        int[] cateType = {
                PickCateType.TYPE_0, // 会员主体
                PickCateType.TYPE_01, // 会员类型
                PickCateType.TYPE_2, // 企业类型
                PickCateType.TYPE_3, // 会员等级
                PickCateType.TYPE_4, // 资质类型
                PickCateType.TYPE_6, // 荣誉分类
                PickCateType.TYPE_7, // 固定资产
                PickCateType.TYPE_8, // 知识产权
                PickCateType.TYPE_9, // 单次业绩最大金额
                PickCateType.TYPE_10,// 是否有招采信息
        };
        boolean isLoadData = true;
        for (int key : cateType) {
            if (isListEmpty(key)) {
                // 除供方会员其余初始化默认都为需方会员  会员类型 0 供方 1需方
                mModel.getLeftChooseData(key, false, mPosition != 1, mNo0);
                isLoadData = false;
            }
        }
        if (scrData == null || scrData.size() == 0) {
            mModel.getAddressModel();  // 经营地址
        }
        return isLoadData;
    }

    private void showChildTab(List<CommonPopEntity> data) {
        isPressTabSelect = false;
        if (data == null || data.size() == 0) {
            mBind.childTab.setVisibility(View.GONE);
            return;
        }
        mBind.popup0.setVisibility(View.GONE);
        mBind.childTab.setVisibility(View.VISIBLE);
        mBind.childTab.removeAllTabs();
        mBind.childTab.clearOnTabSelectedListeners();
        for (int i = 0; i < data.size(); i++) {
            mBind.childTab.addTab(mBind.childTab.newTab().setText(data.get(i).getTypeName()));
        }
        tabSelect(0);
        mBind.childTab.setNormalColor(R.color.color_title_small);
        mBind.childTab.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (!isPressTabSelect) {
                    return;
                }
                int pos = tab.getPosition();
                CommonPopEntity popEntity = mData.get(PickCateType.TYPE_01).getList().get(pos);
                updateMemberSubType(popEntity, pos, false);
                mNo0 = popEntity.getNo();
                mFilters.put(PickCateType.TYPE_01, pos);
                mBind.popup0.setData(popEntity.getChildren(), "");
                if (popEntity.getChildren() == null || popEntity.getChildren().size() == 0) {
                    mBind.popup0.setVisibility(View.GONE);
                } else {
                    mBind.popup0.setVisibility(View.VISIBLE);
                }
                result(mData, mFilters);
            }
        });

    }

    private boolean isPressTabSelect;

    private void tabSelect(int pos) {
        isPressTabSelect = false;
        if (mBind.childTab.getTabCount() > 0) {
            Objects.requireNonNull(mBind.childTab.getTabAt(pos)).select();
            isPressTabSelect = true;
        }
    }

    /**
     * --------------------------------- Popup相关 -------------------------------------------------
     */

    public void initPopup() {
        // 需方会员 ： 经营地址显示，会员等级显示, 企业性质隐藏, 需方会员隐藏
        // 供方会员 ： 经营地址显示，会员等级显示, 企业性质隐藏, 需方会员隐藏
        mBind.popup0.setVisibility(View.GONE);
        mBind.popup1.setVisibility(View.GONE);
        mBind.popup2.setVisibility(View.GONE);
        // 类型 0个人 1企业 2团队
        if (MemberConfig.getInstance().getComType() == 0) {
            mBind.popupMemberLever.setVisibility(View.VISIBLE); // 会员等级
            mBind.popup3.setVisibility(View.GONE); //主体会员
        } else {
            mBind.popupMemberLever.setVisibility(View.GONE);
            mBind.popup3.setVisibility(View.VISIBLE);
        }
        mBind.popup4.setVisibility(View.VISIBLE);
        mBind.popup5.setVisibility(View.GONE);

        mBind.popup0.setKeyName(mMemberSubName);
        // 显示筛选
        mBind.chooseLayout.setVisibility(View.VISIBLE);
        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
        mBind.popup0.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup1.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup2.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup3.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popup5.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.popupMemberLever.initPopup(mBind.grayLayout, mBind.popLine, this);
        // mBind.popup4 经营地址 使用地址Popup 不用会员统一定制Popup
        initAddressPopup();
        mBind.popup5.initPopup(mBind.grayLayout, mBind.popLine, this);
        mBind.chooseLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean otherData = loadOtherData();
                if (otherData) {
                    refreshMemberMain(true, isPersonMember());
                }
            }
        });
    }

    private void initAddressPopup() {
        mBind.popup4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    mModel.getAddressModel();
                    return;
                }
                mBind.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(mNo4) || !TextUtils.isEmpty(mNo41)) {
                    mBind.popup4.updateChooseTextStatus(-2, null);
                } else {
                    mBind.popup4.updateChooseTextStatus(-1, mBind.popup4.getKeyName());
                }
                mAddressPop.showPopwindow0(mBind.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo4 = "";
                mNo41 = "";
                mBind.popup4.updateChooseTextStatus(0, mBind.popup4.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo4 = entity.getProvinceNo();
                    mBind.popup4.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mNo41 = entity.getCityNo();
                        mBind.popup4.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBind.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo4) || !TextUtils.isEmpty(mNo41)) {
                mBind.popup4.updateChooseTextStatus(1, null);
            } else {
                mBind.popup4.updateChooseTextStatus(0, mBind.popup4.getKeyName());
            }
        });
    }

    // Popup 按照分类加载数据
    @Override
    public void onLoadChooseData(String mKeyName) {
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            String value = mNameArray.get(key);
            if (TextUtils.equals(mKeyName, value)) {
                mModel.getLeftChooseData(key, false, mPosition != 1, mNo0);
                return;
            }
        }
    }

    // Popup Item点击事件
    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        int i = mFilters.get(PickCateType.TYPE_01);
        if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_01))) {
            // 会员类型
            if (i != position) {
                refreshItemValue(PickCateType.TYPE_01, position);
                updateMemberSubType(mData.get(PickCateType.TYPE_01).getList().get(position), position, false);
                result(mData, mFilters);
            }
        } else if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_1))) {
            // 会员类型二级
            refreshItemValue(PickCateType.TYPE_1, position);
            updateMultiMemberSubType(PickCateType.TYPE_1, entity, position, false);
            loadData(false);
        } else if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_3))) {
            // 会员等级
            refreshItemValue(PickCateType.TYPE_3, position);
            loadData(false);
        } else if (mKeyName.equals(mNameArray.get(PickCateType.TYPE_2))) {
            // 企业性质
            refreshItemValue(PickCateType.TYPE_2, position);
            loadData(false);
        } else if (mKeyName.equals(mBind.popup3.getKeyName())) {
            // 会员主体
            refreshItemValue(PickCateType.TYPE_0, position);
            refreshMemberMain(false, isPersonMember());
        }
    }

    // 经营地址回调
    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            if (TextUtils.isEmpty(mAddressCurName)) {
                mAddressPop.setData(data, true);
            } else {
                mAddressPop.setDataAndPosition(data, mAddressCurName, "", "", true, true);
            }
        } else {
            mModel.getAddressModel();
        }

    }

    public void showLeftChooseDialog(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        mChooseDialog.addEntity(type, data);
        mChooseDialog.showDialog();
    }

    public void setLeftChooseData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_0:
                // 会员主体
                mBind.popup3.setData(data);
                break;
            case PickCateType.TYPE_01:
                // 底部弹框数据刷新
                mPotionData = new ArrayList<>();
                mPotionData.addAll(data);
                mPotionData.remove(0); // 取消全部
                mBind.popup1.setData(data);
                if (mPosition == 0 || mPosition == 1) {
                    showChildTab(data);
                }
                break;
            case PickCateType.TYPE_1:
                // 会员类型二级
                mBind.popup0.setData(data);
                mBind.popup0.refreshChoose(mNo0, "", 0);
                mBind.popup0.setVisibility(View.VISIBLE);
                break;
            case PickCateType.TYPE_2:
                // 企业类型
                mBind.popup2.setData(data);
                break;
            case PickCateType.TYPE_3:
                // 会员等级
                mBind.popupMemberLever.setData(data);
                break;
            case PickCateType.TYPE_4:
                // 资质类型
                break;
            case PickCateType.TYPE_5:
                break;
            case PickCateType.TYPE_6:
                // 荣誉分类
                break;
            case PickCateType.TYPE_7:
                // 固定资产
                break;
            case PickCateType.TYPE_8:
                // 知识产权
                break;
            case PickCateType.TYPE_9:
                // 单次业绩最大金额
                break;
            case PickCateType.TYPE_10:
                // 是否有招采信息，1有0没有
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
    }

    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    public void addMainEntity(int index, String name, List<CommonPopEntity> list) {
        if (!TextUtils.isEmpty(name)) {
            mNameArray.put(index, name);
        }
        if (mData.get(index) != null) {
            mData.get(index).setTypeName(mNameArray.get(index));
            if (list == null || list.size() == 0) {
                mData.get(index).setList(new ArrayList<>());
            } else {
                mData.get(index).setList(list);
            }
        } else {
            mData.put(index, new XChooseEntity(index, mNameArray.get(index), list));
        }
        mFilters.put(index, 0);
    }

    /**
     * ------------------------------------ 侧滑刷选 ----------------------------------------
     */

    private XChooseDialog mChooseDialog;
    // 数据集
    private final SparseArray<XChooseEntity> mData = new SparseArray<>();
    // 本地缓存筛选结果
    private SparseIntArray mFilters = new SparseIntArray();
    private SparseArray<String> mNameArray;
    // 存储会员关联数据index
    private List<Integer> mMultiKey;
    private final String mMemberSubName = "会员子类";

    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_0, "会员主体");
        mNameArray.put(PickCateType.TYPE_01, "会员类型");
        mNameArray.put(PickCateType.TYPE_1, mMemberSubName);
        mNameArray.put(PickCateType.TYPE_2, "企业性质");
        mNameArray.put(PickCateType.TYPE_3, "会员等级");
        mNameArray.put(PickCateType.TYPE_4, "资质类型");
        mNameArray.put(PickCateType.TYPE_5, "资质等级");
        mNameArray.put(PickCateType.TYPE_6, "荣誉分类");
        mNameArray.put(PickCateType.TYPE_7, "固定资产");
        mNameArray.put(PickCateType.TYPE_8, "知识产权");
        mNameArray.put(PickCateType.TYPE_9, "单次业绩最大金额");
        mNameArray.put(PickCateType.TYPE_10, "是否有招采信息");
        mMultiKey = new ArrayList<>();
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }

    private boolean isListEmpty(int catType) {
        return mData.get(catType) == null ||
                (mData.get(catType).getList() == null || mData.get(catType).getList().size() == 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {
        switch (entity.getSort()) {
            case PickCateType.TYPE_0: // 会员字体
                refreshMemberMain(true, isLeftDialogPersonMember(entity.getItemNo(pos)));
                break;
            case PickCateType.TYPE_01:
                updateMemberSubType(entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            case PickCateType.TYPE_1:
                updateMultiMemberSubType(entity.getSort(), entity.getList().get(pos), pos, true);
                mChooseDialog.showDialog();
                break;
            default:
                if (mMultiKey.contains(entity.getSort())) {
                    updateMultiMemberSubType(entity.getSort(), entity.getList().get(pos), pos, true);
                    mChooseDialog.showDialog();
                }
                break;
        }
    }

    private void updateMemberSubType(CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        mBind.popup0.setKeyName(mMemberSubName);
        if (isShowLeftDialog) {
            mChooseDialog.addEntity(PickCateType.TYPE_1, mMemberSubName, tempList);
            for (Integer integer : mMultiKey) {
                mChooseDialog.addEntity(integer, mMemberSubName, tempList);
            }
        } else {
            addMainEntity(PickCateType.TYPE_1, mMemberSubName, tempList);
            for (Integer integer : mMultiKey) {
                addMainEntity(integer, mMemberSubName, tempList);
            }
        }
        if (pos > 0) {
            if (entity.getChildren() != null && entity.getChildren().size() > 0) {
                if (!entity.getChildren().get(0).getTypeName().equals("全部")) {
                    entity.getChildren().add(0, new CommonPopEntity("", "全部"));
                }
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(PickCateType.TYPE_1, mMemberSubName, entity.getChildren());
                } else {
                    addMainEntity(PickCateType.TYPE_1, mMemberSubName, entity.getChildren());
                }
            }
        }
    }

    private void updateMultiMemberSubType(int sort, CommonPopEntity entity, int pos, boolean isShowLeftDialog) {
        List<CommonPopEntity> tempList = new ArrayList<>();
        if (isShowLeftDialog) {
            for (Integer integer : mMultiKey) {
                if (sort < integer) {
                    mChooseDialog.addEntity(integer, mMemberSubName, tempList);
                }
            }
        } else {
            for (Integer integer : mMultiKey) {
                if (sort < integer) {
                    addMainEntity(integer, mMemberSubName, tempList);
                }
            }
        }
        if (pos > 0) {
            if (entity.getChildren() != null && entity.getChildren().size() > 0) {
                if (!entity.getChildren().get(0).getTypeName().equals("全部")) {
                    entity.getChildren().add(0, new CommonPopEntity("", "全部"));
                }
                int newSort = sort == PickCateType.TYPE_1 ? getMultiKey() : sort + 1;
                mMultiKey.add(newSort);
                if (isShowLeftDialog) {
                    mChooseDialog.addEntity(newSort, mMemberSubName, entity.getChildren());
                } else {
                    addMainEntity(newSort, mMemberSubName, entity.getChildren());
                }
            }
        }
    }

    private int getMultiKey() {
        return PickCateType.TYPE_1 * 10;
    }

    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        for (int i = 0; i < data.size(); i++) {
            int keyAt = data.keyAt(i);
            if (keyAt != PickCateType.TYPE_2// 企业类型
                    && keyAt != PickCateType.TYPE_4// 资质类型
                    && keyAt != PickCateType.TYPE_6// 荣誉分类
                    && keyAt != PickCateType.TYPE_7// 固定资产
                    && keyAt != PickCateType.TYPE_8// 知识产权
                    && keyAt != PickCateType.TYPE_9// 单次业绩最大金额
                    && keyAt != PickCateType.TYPE_10) {// 是否有招采信息
                mData.put(keyAt, data.get(keyAt));
            }
        }
        mFilters = map.clone();
        for (int i = 0; i < mData.size(); i++) {
            int key = mData.keyAt(i);
            refreshItemValue(key, mFilters.get(key));
        }
        if (isPersonMember()) {
            initPersonAdapter();
        } else {
            initCompanyAdapter();
        }
        loadData(false);
    }

    private void refreshItemValue(int key, int value) {
        XChooseEntity entity = mData.get(key);
        mFilters.put(key, value);
        String itemNo = entity.getItemNo(value);
        String itemId = entity.getItemId(value);
        switch (key) {
            case PickCateType.TYPE_0: // 会员类型
                if (!TextUtils.equals(itemNo, mNo01)) {
                    mNo01 = itemNo;
                    mBind.popup3.refreshChoose(mNo01, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_01: // 会员类型
                if (!TextUtils.equals(itemNo, mNo0)) {
                    mNo0 = itemNo;
                    mBind.popup1.refreshChoose(mNo0, entity.getItemName(value), value);
                    tabSelect(value);
                    if (isListEmpty(PickCateType.TYPE_1)) {
                        mBind.popup0.setVisibility(View.GONE);
                    } else {
                        mBind.popup0.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case PickCateType.TYPE_1: // 会员类型二级
                if (!TextUtils.equals(itemNo, mNo1)) {
                    mNo1 = itemNo;
                    mBind.popup0.refreshChoose(mNo1, entity.getItemName(value), value);
                    mBind.popup0.setData(entity.getList(), mNo1);
                    if (isListEmpty(PickCateType.TYPE_1)) {
                        mBind.popup0.setVisibility(View.GONE);
                    } else {
                        mBind.popup0.setVisibility(View.VISIBLE);
                    }
                }
                break;
            case PickCateType.TYPE_2: // 企业类型
                String itemName = value == 0 ? "" : entity.getItemName(value);
                if (!TextUtils.equals(itemName, mNo2)) {
                    mNo2 = itemName;
                    mBind.popup2.refreshChoose(mNo2, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_3: // 会员等级
                if (!TextUtils.equals(itemId, mNo3)) {
                    mNo3 = entity.getItemId(value);
                    mBind.popupMemberLever.refreshChoose(mNo3, entity.getItemName(value), value);
                }
                break;
            case PickCateType.TYPE_4:     //  "资质类型");
                mNo5 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_5:     //  "资质类型");
                mNo51 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_6:        // "荣誉分类");
                mNo6 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_7:      //  "固定资产");
                mNo7 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_8:// "知识产权");
                mNo8 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_9:      // "单次业绩最大金额");
                mNo9 = entity.getItemNo(value);
                break;
            case PickCateType.TYPE_10:        // "是否有招采信息");
                mNo10 = entity.getItemNo(value);
                break;
            default:
                if (mMultiKey.contains(key) && value > 0) {
                    mNo1 = itemNo;
                }
                break;
        }
    }

    private void refreshMemberMain(boolean isShowDialog, boolean isPersonCompany) {
        SparseIntArray intArray = new SparseIntArray();
        if (isShowDialog) {
            SparseArray<XChooseEntity> mTemp = new SparseArray<>();
            if (isPersonCompany) {
                // 个人企业，过滤展示的选项
                for (int i = 0; i < mData.size(); i++) {
                    int keyAt = mData.keyAt(i);
                    if (keyAt != PickCateType.TYPE_2// 企业类型
                            && keyAt != PickCateType.TYPE_4// 资质类型
                            && keyAt != PickCateType.TYPE_6// 荣誉分类
                            && keyAt != PickCateType.TYPE_7// 固定资产
                            && keyAt != PickCateType.TYPE_8// 知识产权
                            && keyAt != PickCateType.TYPE_9// 单次业绩最大金额
                            && keyAt != PickCateType.TYPE_10) {// 是否有招采信息
                        mTemp.put(keyAt, mData.get(keyAt));
                        intArray.put(keyAt, mFilters.get(keyAt));
                    } else {
                        intArray.put(keyAt, 0);
                    }
                }
                intArray.put(PickCateType.TYPE_0, 1);
                mChooseDialog.initData(mTemp, intArray);
            } else {
                mFilters.put(PickCateType.TYPE_0, 0);
                mChooseDialog.initData(mData, mFilters);
            }
            mChooseDialog.showDialog();
        } else {
            if (isPersonCompany) {
                // 个人
                for (int i = 0; i < mData.size(); i++) {
                    int keyAt = mData.keyAt(i);
                    if (keyAt != PickCateType.TYPE_2// 企业类型
                            && keyAt != PickCateType.TYPE_4// 资质类型
                            && keyAt != PickCateType.TYPE_6// 荣誉分类
                            && keyAt != PickCateType.TYPE_7// 固定资产
                            && keyAt != PickCateType.TYPE_8// 知识产权
                            && keyAt != PickCateType.TYPE_9// 单次业绩最大金额
                            && keyAt != PickCateType.TYPE_10) {// 是否有招采信息
                        mFilters.put(keyAt, mFilters.get(keyAt));
                    } else {
                        mFilters.put(keyAt, 0);
                    }
                }
                mFilters.put(PickCateType.TYPE_0, 1);
            } else {
                mFilters.put(PickCateType.TYPE_0, 0);
            }
            result(mData, mFilters);
        }
    }

    @Override
    public void reset() {
        mFilters.clear();
        addMainEntity(PickCateType.TYPE_1, new ArrayList<>());
        for (Integer integer : mMultiKey) {
            addMainEntity(integer, new ArrayList<>());
        }
        mBind.popup0.setVisibility(View.GONE);
        result(mData, mFilters);
        refreshMemberMain(true, false);
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData, mFilters);
    }

    /**
     * initRecycler
     */
    private void initRecycler() {
        TextView textView = mBind.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBind.recyclerView.setPullRefreshEnabled(true);
        mBind.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBind.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBind.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        if (isPersonMember()) {
            initPersonAdapter();
        } else {
            initCompanyAdapter();
        }
        mBind.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
    }

    private void initPersonAdapter() {
        mPersonAdapter = new MemberCommonPersonAdapter(getContext(), null, mPosition, this);
        mBind.recyclerView.setAdapter(mPersonAdapter);
        mPersonAdapter.setOnItemClick(new AdapterOnItemClick<MemberPersonBean>() {
            @Override
            public void onItemClick(MemberPersonBean memberPersonBean, int position) {
                if (!TextUtils.isEmpty(memberPersonBean.userNo)) {
                    MemberConfig.getInstance().startWebsiteInfo(getActivity(), memberPersonBean.userNo, 0);
                } else {
                    MToast.showToast(getActivity(), "个人No为空");
                }
            }
        });
        mPersonAdapter.setListener(new MemberCommonPersonAdapter.IFollowListener() {
            @Override
            public void onFollow(int pos, MemberBean bean) {
                mModel.userFocus(bean.getCompanyNo(), bean.isFocused(), pos);
            }
        });
    }

    private void initCompanyAdapter() {
        myMemberAdapter = new MemberCommonAdapter(getContext(), null, mPosition, this);
        mBind.recyclerView.setAdapter(myMemberAdapter);
        myMemberAdapter.setOnItemClick(new AdapterOnItemClick<MemberBean>() {
            @Override
            public void onItemClick(MemberBean memberBean, int position) {
                // 1供方会员 2需方会员
                if (mPosition == 0) {
                    memberBean.setMemberUpdateLeverType("2");
                } else if (mPosition == 1) {
                    memberBean.setMemberUpdateLeverType("1");
                }
                // MemberCompanyWebActivity.start(getActivity(), memberBean);
                if (!TextUtils.isEmpty(memberBean.getCompanyNo())) {
                    MemberConfig.getInstance().startWebsiteInfo(getActivity(), memberBean.getCompanyNo(), 1);
                } else {
                    MToast.showToast(getActivity(), "店铺No为空");
                }
            }
        });
        myMemberAdapter.setListener(new MemberCommonAdapter.IFollowListener() {
            @Override
            public void onFollow(int pos, MemberBean bean) {
                mModel.userFocus(bean.getCompanyNo(), bean.isFocused(), pos);
            }
        });
    }

    private boolean isPersonMember() {
        return TextUtils.equals("0", mNo01);
    }

    private boolean isLeftDialogPersonMember(String no) {
        return TextUtils.equals("0", no);
    }

    public void showEmpty() {
        mBind.recyclerView.setVisibility(View.GONE);
        mBind.emptyView.setVisibility(View.VISIBLE);
    }

    public <T> void refreshRecycler(List<T> list, boolean isLoadMore, boolean isLastPage) {
        BaseRecycleAdapter<T> adapter;
        if (isPersonMember()) {
            adapter = (BaseRecycleAdapter<T>) mPersonAdapter;
        } else {
            adapter = (BaseRecycleAdapter<T>) myMemberAdapter;
        }
        mBind.recyclerView.setVisibility(View.VISIBLE);
        if (isLoadMore) {
            mBind.recyclerView.loadMoreComplete();
            if (list != null && list.size() > 0) {
                adapter.addDatas(list);
            }
            mBind.recyclerView.setNoMore(isLastPage);
        } else {
            mBind.recyclerView.refreshComplete();
            if (list != null && list.size() > 0) {
                mBind.emptyView.setVisibility(View.GONE);
                adapter.setDatas(list);
            } else {
                adapter.clearDatas();
                mBind.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onMemberTransfer(int pos, MemberBean bean) {
        if (bean == null || TextUtils.isEmpty(bean.getLevel())) {
            MToast.showToast(getContext(), "会员等级不能为空.");
            return;
        }
        mModel.getProcessStatus(pos, "memberEvaluate", bean);
    }

    @Override
    public void onMemberDissolution(int pos, MemberBean bean) {
        mModel.getProcessStatus(pos, "memberRelieve", bean);
    }

    private MemberBean mModifyBean;

    @Override
    public void onMemberModify(int pos, MemberBean bean) {
        mModifyBean = bean;
        // 0 供方 1需方
        ChooseMemberTypeActivity.start(getActivity(), mPosition == 0 ? "1" : "0", MemberConfig.REQ_MEMBER_TYPE);
    }


    @Override
    public void onMore(int pos, MemberBean bean, ImageView imageView) {
        mModifyBean = bean;
        showPopupWindow(imageView,bean,pos);
    }


    // 更新会员类型回调
    public void updateMemberType(MemberBean bean) {
        for (MemberBean data : myMemberAdapter.getDatas()) {
            if (data.getNo().equals(bean.getNo())) {
                data.setAllCategoryName(bean.getAllCategoryName());
                myMemberAdapter.notifyDataSetChanged();
            }
        }
    }

    // 解除会员回调
    public void removeMember(int pos, MemberBean bean) {
        if (isPersonMember()) {
            mPersonAdapter.getDatas().remove(pos);
            mPersonAdapter.notifyDataSetChanged();
        } else {
            myMemberAdapter.getDatas().remove(pos);
            myMemberAdapter.notifyDataSetChanged();
        }
    }

    // 会员调级回调
    public void updateMemberLevel(int pos, MemberBean bean) {
        if (isPersonMember()) {
            mPersonAdapter.getDatas().get(pos).userLevel = bean.getLevel();
            mPersonAdapter.notifyDataSetChanged();
        } else {
            myMemberAdapter.getDatas().get(pos).setLevel(bean.getLevel());
            myMemberAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 已关注回调
     */
    @SuppressLint("NotifyDataSetChanged")
    public void updateMemberFollow(boolean isGz, int position) {
        myMemberAdapter.getDatas().remove(position);
        myMemberAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_MEMBER_TYPE) {
            List<CommonPopEntity> memberTypes = (List<CommonPopEntity>) intent.getSerializableExtra("MEMBER_DATA");
            mModel.updateMemberType(mPosition, mModifyBean, memberTypes);
        }
    }

    private void showPopupWindow(View view, MemberBean bean,int pos) {
        View contentView = LayoutInflater.from(getContext()).inflate(
                R.layout.pop_window, null);
        // 设置按钮的点击事件
        TextView tv_modify = contentView.findViewById(R.id.tv_modify);
        tv_modify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle =new Bundle();
                bundle.putSerializable("bean",bean);
                bundle.putString("checkType",mNo01);
                MemberModifyActivity.start(requireActivity(),bundle);
            }
        });
        TextView tv_jie_chu = contentView.findViewById(R.id.tv_jie_chu);
        tv_jie_chu.setOnClickListener(v -> {
            mModel.getProcessStatus(pos, "memberRelieve", bean);//解除
        });

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.mipmap.more_pop));

        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);

    }
}
